<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2023/5/4
 * Time: 13:54
 * Desc: 日息宝
 */
declare (strict_types=1);

namespace app\command;

use app\extend\model\Level;
use app\extend\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class Rixibao extends Command
{
    protected function configure()
    {
        $this->setName('rixibao')->setDescription('处理日息宝订单');
    }

    protected function execute(Input $input, Output $output)
    {
        $userArr = User::where([
            ['rixibao_money', '=', 0]
        ])->field('id,rixibao_money,level_id')->select()->toArray();

        if (empty($userArr)) {
            exit('暂无日息宝处理');
        }

        foreach ($userArr as $userVal) {

            //判断用户当天有没有结息
            $rixibaoInfo = \app\extend\model\Rixibao::where([
                ['uid', '=', $userVal['id']],
                ['type', '=', 3],
                ['created_at', 'between', [date('Y-m-d'), date('Y-m-d 23:59:59')]]
            ])->find();
            if (!empty($rixibaoInfo)) {
                continue;
            }

            $levelInfo = Level::where([
                ['id', '=', $userVal['level_id']]
            ])->find();

            echo "用户ID" . $userVal['id'] . "\n";

            try {
                // 启动事务
                Db::startTrans();

                \app\extend\model\Rixibao::insert([
                    'uid' => $userVal['id'],
                    'type' => 3,
                    'money' => $userVal['rixibao_money'] * ($levelInfo['rixibao_rate'] / 100),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                User::where([
                    ['id', '=', $userVal['id']]
                ])->update([
                    'rixibao_money' => $userVal['rixibao_money'] + ($userVal['rixibao_money'] * ($levelInfo['rixibao_rate'] / 100)),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                Db::commit();
                echo "日息宝处理成功\n";
            } catch (\Exception $e) {
                Db::rollback();
                echo "日息宝处理失败，错误" . $e->getMessage() . "\n";
            }
        }
    }
}